<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-alert
      title="注意：只允许第三级分类设置相关参数"
      type="warning"
      show-icon
      center
    >
    </el-alert>
    <div>
      选择商品分类:
      <el-cascader
        v-loading="typeList.length === 0"
        v-model="getChooseTypeId"
        :options="typeList"
        :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }"
        @change="handleChange"
      >
      </el-cascader>
    </div>
    <!-- 
        v-model=activeName:绑定选项卡的选中项的name
     -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="动态参数" name="many" :disabled="compDis">
        <el-button
          type="primary"
          size="small"
          :disabled="compDis"
          @click="paramsDialogVisble = true"
          >添加参数</el-button
        >
        <el-table :data="manyData" border>
          <el-table-column type="expand">
            <template slot-scope="{ row }">
              <el-tag
                v-for="(item, index) in row.attr_vals"
                :key="index" 
                closable
                @close="delTag(row,index)"
                style="margin: 5px"
                >{{ item }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作" prop="attr_name">
            <template slot-scope="{row}">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="paramsedit=true;editDialog(row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="静态属性" name="only" :disabled="compDis">
        <el-button
          type="primary"
          size="small"
          :disabled="compDis"
          @click="paramsDialogVisble = true"
          >添加属性</el-button
        >
        <el-table :data="onlyData" border>
          <el-table-column type="expand">
            <template slot-scope="{ row }">
              <el-tag
                v-for="(item, index) in row.attr_vals"
                :key="index"
                closable
                @close="delTag(row,index)"
                style="margin: 5px"
                >{{ item }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="`添加${dialogTit}`"
      :visible.sync="paramsDialogVisble"
      @close="$refs.pform.resetFields()"
    >
      <!-- 如果想用 表单方法重置 表单的内容，form要有 :model ,item上要有prop -->
      <el-form ref="pform" :model="paramsForm" label-width="90px">
        <el-form-item :label="dialogTit" prop="attr_name">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            dialogVisible = false;
            addParams();
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      :title="`修改${dialogTit}`"
      :visible.sync="paramsedit"
      @close="$refs.editform.resetFields()"
    >
      <el-form
        :model="editform"
        label-width="90px"
        ref="editform"
      >
        <el-form-item :label="dialogTit" prop="attr_name">
          <el-input v-model="editform.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="paramsedit=false">取消</el-button>
          <el-button type="primary" @click="paramsedit=false;editParams()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      paramsForm: {
        // 添加参数数据
        attr_name: "",
      },
      editform:{
        attrId:'',
        // 修改参数数据
        attr_name: "",
      },
      paramsedit:false,
      paramsDialogVisble: false, // 添加参数对话框开关
      typeList: [], // 三级分类的数据
      getChooseTypeId: [], // 选中的分类id
      activeName: "many", // 选项卡选中对应的name值
      onlyData: [], // 动态参数数据
      manyData: [], // 静态属性数据
    };
  },
  methods: {
    // 点击添加tag标签按钮的处理函数
    showInput(row) {
      row.inputVisible = true;
    },
    // 动态添加tag 标签的菜单 回车事件及 失焦事件的处理函数
    handleInputConfirm(row) {
      if (row.inputValue.trim() == "") {
        row.inputVisible = false; 
        row.inputValue = "";
        return;
      }
      // 给当前行的att_vals数据添加一个新的标签内容，后续会发送给接口进行存储
      // "12123 abc" = ["12123","abc"].join('') = '12123abc'
      row.attr_vals.push(row.inputValue.trim());
      row.inputVisible = false;
      row.inputValue = "";
      this.saveAttrs(row);
    },
    // 删除参数下的指定标签
    delTag(row,index){
        row.attr_vals.splice(index,1)
        this.saveAttrs(row);
    },
    async del(row){
      const {data:{meta}} = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`);
      if(meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParams();
    },
    async saveAttrs(row) {
      const {
        data: { meta },
      } = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(" "), // 默认读的[] array类型,但接口需要的字符串，所以要转换
      });
      if (meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success("更新成功");
    },
    // 添加参数(请求接口)
    async addParams() {
      const {
        data: { meta },
      } = await this.$http.post(`categories/${this.catId}/attributes`, {
        attr_name: this.paramsForm.attr_name,
        attr_sel: this.activeName,
      });
      if (meta.status !== 201) return this.$message.error("添加参数失败");
      this.$message.success("添加参数成功");
      this.paramsDialogVisble = false;
      this.getParams();
    },
    // 编辑对话框
    editDialog(row){
      this.editform.attrId=row.attr_id
      this.editform.attr_name=row.attr_name
    },
    // 确认编辑
    async editParams(){
      const {data:{meta}} = await this.$http.put(`categories/${this.catId}/attributes/${this.editform.attrId}`,{attr_name:this.editform.attr_name,attr_sel:this.activeName})
      if(meta.status!==200) return this.$message.error("修改参数失败");
      this.$message.success("修改参数成功");
      this.getParams();
    },
    // 三级分类选择变化是的处理函数
    handleChange() {
      // 获取参数列表数据
      this.getParams();
    },                            
    // 选项标签页，在选项被选中时触发
    handleClick() {
      // 获取参数列表数据
      this.getParams();
    },
    async getParams() {
      const {
        data: { data, meta },
      } = await this.$http.get(`categories/${this.catId}/attributes`, {
        params: { sel: this.activeName },
      });
      if (meta.status !== 200) return this.$message.error("获取参数列表失败");
      data.forEach((item) => {
        // item.attr_vals = "49时4k超薄面膜 人工智能,55时4K观影曲面 30核HDR,55时4K超薄面膜 人工智能,65时4K超薄面膜 人工智能"
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // item.attr_vals = ["49时4k超薄曲面","人工智能，55时4k观影曲面",.....]
        // 每一条数都要有自己的input框是否显示
        item.inputVisible = false;
        // 每一条数据都要有自己的input框的值
        item.inputValue = "";
      });
      if (this.activeName == "only") {
        this.onlyData = data;
      } else if (this.activeName == "many") {
        this.manyData = data;
      }
    },
    // 获取三级分类数据
    async getTypeList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取分类数据失败");
      this.typeList = res.data;
    },
  },
  computed: {
    // 通过 activeName 计算对话框标题 文本内容 动态参数 或静态属性
    dialogTit() {
      return this.activeName == "many" ? "动态参数" : "静态属性";
    },
    // 通过选择分类，默认getChooseTypeId得到的是三级都有的id[1,2,3],需要通过getChooseTypeId,计算出第三级的id
    catId() {
      if (this.getChooseTypeId.length === 3) {
        return this.getChooseTypeId[2];
      } else {
        return 0;
      }
    },
    // 通过 getChooseTypeId 计算出是否禁用,如果已经选择了三级分类，数组长度必须是3，解除禁用，不然禁用
    compDis() {
      if (this.getChooseTypeId.length == 3) {
        return false;
      } else {
        return true;
      }
    },
  },
  created() {
    this.getTypeList();
  },
};
</script>